const app = getApp()
import { getScoring, addScore, addStatistics, getGameScoring, addGameScore,deleteGameScore ,deleteScore} from '../../../http/caddie'

import { fillRange } from '../../../utils/utils'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        selectOpen: ["成绩", "进程"],
        _num: 0,
        staticUrl: app.globalData.staticUrl,
        scorecards: [],

        playerScoresDisplay: [],
        isGame: false
    },
    pageData: { //不渲染到页面的全局变量
        match_id: '',
        round_id: '',
        group_id: '',
        ca_id: ''
    },
    /**
     * 生命周期函数--监听页面加载
     */

    onLoad: function(options) {

        
        let { match_id, round_id, group_id } = options

        if(options.scene)
        { 
            var scenes =  decodeURIComponent(options.scene).split('&');
            if(options.scene){
                match_id = scenes[0].split('=')[1];
            }
        }
        // if (!wx.getStorageSync('caddieInfo')) {
        //     wx.redirectTo({
        //         url: `../scoring?match_id=${match_id}&round_id=${round_id}&group_id=${group_id}`,
        //     })
        // }
        console.log(options);
        this.pageData = { match_id, round_id, group_id }
        if (!round_id && !group_id) {
            this.setData({ isGame: true })
        }
        this.pageData.ca_id = wx.getStorageSync('caddieInfo').ca_id||6
        this.getScoring()
    },
    // 获取成绩数据
    async getScoring() {
        const { match_id, round_id, group_id, ca_id } = this.pageData
        const params = { match_id, round_id, group_id, ca_id }
        console.log(params);
        const methods = this.data.isGame ? getGameScoring : getScoring
        methods(JSON.parse(JSON.stringify(params))).then(res => {
            console.log(res);
            if (res.errorcode.code === 'ok') {
                const { end_hole, holepars, scorecards, score, start_hole, gp_seq, mt_cn_name } = res.data
                //球洞 & 球洞标准值
              //  const holes = hole_list.map(item => { return item.ho_id })
               // const hole_par = hole_list.length > end_hole ? hole_list.splice(end_hole) : hole_list
              //  const par_total = hole_par.reduce((prev, next) => { return prev + next.ho_par }, 0)

                this.setData({
                    
                    gp_seq,
                    scorecards,
                    mt_cn_name,
                    hole_list:holepars,
                    start_hole,
                    end_hole,
                })
               
                //console.log(player_info);
                //console.log(holes);
                
                this.changeScoresDisplay()
            }
        })
    },

    

    computedScore(scorecards) {
       
        for (let key in scorecards) {
            let sum = 0
            let topar = 0;
            scorecards[key].holescores.forEach(item => {
                sum += Number(item.holeScore) || 0
                topar += Number(item.holetopar) || 0
            })
            scorecards[key].playerscore = sum;
            scorecards[key].playertopar = topar;
        }
        console.log(scorecards);
        return scorecards
    },
    // 计分展示
    changeScoresDisplay() {
        const { scorecards, hole_list } = this.data
        const playerScoresDisplay = [];
        hole_list.holes.forEach(hole=> {
            const scoreArray = []
            scorecards.forEach(item=> {
                const scoresList = item.holescores;
                const list = scoresList.filter(item => item.holeNo === hole.holeNo)
                if (list.length > 0) {
                    scoreArray.push(list[0])
                } else {
                    scoreArray.push({})
                }
            })
            const obj = { hole_id: hole.holeNo, scores: scoreArray }
            playerScoresDisplay.push(obj)
        })
        this.setData({
            playerScoresDisplay: playerScoresDisplay,
        });
        console.log(playerScoresDisplay);
    },
    switchChange(_ref) {
        var currentTarget = _ref.currentTarget;
        var tab = currentTarget.dataset.index;
        if (tab == "0") {
            this.setData({
                _num: 0,
            })
        } else {
            this.setData({
                _num: 1,
            })
        }
        //this.changeScoresDisplay();
    },
    // 显示记分板
    showCoachPopup(e) {
        const { hole_index, player_index, score } = e.currentTarget.dataset
        const current_par = this.data.hole_list.holes[hole_index].holePar
        const current_score = score || 0
        console.log(current_par);
        this.setData({ current_par, current_score, hole_index, player_index })
        this.selectComponent("#popup-coach").showPopup();
    },

    //取消事件
    _errorCoach() {
        this.selectComponent("#popup-coach").hidePopup();
    },
    //确认事件
    _successCoach(e) {
        const score = e.detail
        this.handleShowScore(score)
    },
    _openMore() {
        this.selectComponent("#popup-coach").hidePopup();
        this.selectComponent("#popup").showPopup();
        var scoredata = this.data.scorecards[this.data.player_index].holescores[this.data.hole_index];
        this.selectComponent("#popup").setForm(scoredata);
    },
    //取消事件
    _error() {
        this.selectComponent("#popup").hidePopup();
        this.selectComponent("#popup-coach").showPopup();
    },
    _clearScore() {
        var score =null;
        // 用户点击了确定属性的按钮，对应选择了'男'
        this.handleShowScore(score)
               
       
    },
    //确认事件
    _success(e) {
        const { player_index, hole_index, scorecards, hole_list } = this.data
        const player_id = scorecards[player_index].player.pl_id
        const hole = hole_list.holes[hole_index].holeNo
        const params = Object.assign(this.pageData, e.detail, { player_id, hole })
        console.log(params);
        var that = this;
        addStatistics(params).then(res => {
            if (res.errorcode.code == 'ok') {
                wx.showToast({
                    title: '数据统计成功',
                    icon: 'none',
                    duration: 2000
                })
                scorecards[player_index].holescores[hole_index].putts =  e.detail.putts; //推杆
                scorecards[player_index].holescores[hole_index].fairway =  e.detail.fairway;//上球道(1:勾选，0未勾选)
                scorecards[player_index].holescores[hole_index].distance =  e.detail.distance;
                scorecards[player_index].holescores[hole_index].bunker =  e.detail.bunker;
                that.setData({scorecards});
                this.selectComponent("#popup").hidePopup();
            }
        })
    },
    async handleShowScore(score) {
        let { scorecards, hole_index, player_index, hole_list, current_par, current_score, hole_par, end_hole } = this.data
        const paramsObj = {
            score,
            hole: hole_list.holes[hole_index].holeNo,
            player_id: scorecards[player_index].player.pl_id,
            ho_par:current_par,
        }

        const scoreObj = {
            hole_id: hole_list.holes[hole_index].holeNo,
            score,
            topar: Number(score - current_par) || 0
        }
        //当前球洞是否已存在分数
        const ho_index = scorecards[player_index].holescores.findIndex(item => item.holeNo === paramsObj.hole)
        /*
        if (ho_index > -1) {
            playerScores[paramsObj.player_id][ho_index] = scoreObj;
           
        } else {
            playerScores[paramsObj.player_id].push(scoreObj)
        }*/

        var that = this;
       
        var  comfirmstr = scorecards[player_index].player.pl_cn_name + '\r\n 第<'+ hole_list.holes[hole_index].holeNo +'>洞成绩为<'
            +score + '>杆 \r\n 请确认'  ;
            var title ="请确认成绩？";
            if(!score){
                comfirmstr = "是否删除 <" + scorecards[player_index].player.pl_cn_name + '>\r\n 第<'+ hole_list.holes[hole_index].holeNo+'>洞的成绩 请确认'  ;
                 title = "请确认是否删除?";
            }
            wx.showModal({
                title: title,
                content: comfirmstr,
                cancelText:'取消',
                confirmText:'确认',
                success:async function(res){
                  if(res.cancel){
                    // 用户点击了取消属性的按钮，对应选择了'女'
                    return false;
                  }else if(res.confirm){
                    // 用户点击了确定属性的按钮，对应选择了'男'
                    
                    if (score) {
                        // 录入分数
                        const params = Object.assign(paramsObj, that.pageData)
                        params.isgame  = (that.data.isGame)?1:0;

                        console.log(params);
                        const methods = that.data.isGame ? addGameScore : addScore
                        await methods(JSON.parse(JSON.stringify(params)))
                    } else {
                        const params = Object.assign(paramsObj, that.pageData)
                        params.isgame  = (that.data.isGame)?1:0;
                        console.log(params);
                        const methods = that.data.isGame ? deleteGameScore : deleteScore
                        await methods(JSON.parse(JSON.stringify(params)))
                       // await deleteScore(params) // 删除分数
                    }
                    scorecards[player_index].holescores[hole_index].holeScore = score;
                    scorecards[player_index].holescores[hole_index].holetopar = score?scoreObj.topar:'';
                    current_par = hole_list.holes[hole_index].holePar
                    current_score = scorecards[player_index].holescores.filter(item => item.holeNo === hole_list.holes[hole_index].holeNo)[0].holeScore
                    scorecards = that.computedScore(scorecards)
                    console.log(scorecards);
                    //console.log(total);
                    if (player_index === scorecards.length - 1) {
                        if (end_hole === hole_index + 1) {
                            that.selectComponent("#popup-coach").hidePopup()
                        } else {
                          if(hole_index == 18){
                            hole_index = 1
                          }
                          else{
                            hole_index += 1
                            player_index = 0
                          }
                        }
                    } else {
                        player_index += 1
                    }
                    current_par = hole_list.holes[hole_index].holePar
                    current_score = scorecards[player_index].holescores.filter(item => item.holeNo === hole_list.holes[hole_index].holeNo)[0].holeScore
                   
                   that.setData({ scorecards, current_score, current_par, player_index, hole_index })
                    setTimeout(() => {
                        that.changeScoresDisplay()
                    }, 0)
                  }
                  else{
                      return false;
                  }
                }
              })
           

            

       
    },

   

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },
})